#include "RefactCleaner.h"
#include <Poco\File.h>
#include <Poco\Path.h>
#include "Poco\Util\PropertyFileConfiguration.h"
#include "Poco\RecursiveDirectoryIterator.h"
#include <Poco\Util\Application.h>

#include "Util.h"
using Poco::File;
using Poco::Path;
using std::string;
using Poco::Util::Application;
using Poco::SiblingsFirstRecursiveDirectoryIterator;



RefactCleaner::RefactCleaner()
{

}

RefactCleaner::~RefactCleaner()
{

}

void RefactCleaner::cleanSrc()
{
	Application& app = Application::instance();
	Path _srcPath(Path().absolute().pushDirectory(app.config().getString("src")));
	Path _srcsPath(Path().absolute().pushDirectory(app.config().getString("srcs")));
	string _srcPathName = _srcPath.toString();
	string _srcsPathName = _srcsPath.toString();
	SiblingsFirstRecursiveDirectoryIterator targetit(_srcPath);
	SiblingsFirstRecursiveDirectoryIterator tend;
	std::vector<string> need_delete;
	for (; targetit != tend; ++targetit) {
		File srcf = Util::getSrcsFile(*targetit);
		if (!srcf.exists())
			need_delete.push_back(targetit->path());

	}

	if (need_delete.size() == 0) {
		app.logger().information("All files is sync, nothing need to be delete, bye~");
	}

	for (std::vector<string>::iterator it = need_delete.begin(); it != need_delete.end(); ++it) {
		File f = File(*it);
		if (f.exists()) {
			if (f.isFile())
				app.logger().information("Delete file: %s", f.path());
			else
				app.logger().information("Delete dir: %s", f.path());
			f.remove(true);
		}
	}

}

void RefactCleaner::cleanSrcs()
{
	Application& app = Application::instance();
	Path _srcPath(Path().absolute().pushDirectory(app.config().getString("src")));
	Path _srcsPath(Path().absolute().pushDirectory(app.config().getString("srcs")));
	string _srcPathName = _srcPath.toString();
	string _srcsPathName = _srcsPath.toString();
	SiblingsFirstRecursiveDirectoryIterator targetit(_srcsPath);
	SiblingsFirstRecursiveDirectoryIterator tend;
	std::vector<string> need_delete;
	for (; targetit != tend; ++targetit) {
		File srcf = Util::getSrcFile(*targetit);
		if (!srcf.exists())
			need_delete.push_back(targetit->path());

	}

	if (need_delete.size() == 0) {
		app.logger().information("All files is sync, nothing need to be delete, bye~");
	}
	for (std::vector<string>::iterator it = need_delete.begin(); it != need_delete.end(); ++it) {
		File f = File(*it);
		if (f.exists()) {
			if (f.isFile())
				app.logger().information("Delete file: %s", f.path());
			else
				app.logger().information("Delete dir: %s", f.path());
			f.remove(true);
		}
	}

}
